package com.university.dialog;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.university.utils.Flag;
import com.university.utils.SqliteDatabaseManager;

public class GetHotUniversityDialog {
	private ProgressDialog dialog;
	private SqliteDatabaseManager manager;
	private RequestQueue mQueue;
	private Context mContext;
	public GetHotUniversityDialog(Context context) {
		mContext=context;
		dialog=new ProgressDialog(mContext, ProgressDialog.STYLE_SPINNER);
		dialog.setTitle("提示");
		dialog.setMessage("正在更新数据，请稍等...");
		dialog.setCancelable(false);
		dialog.show();
		manager=SqliteDatabaseManager.getInstance(mContext);
	    //网络volley框架相关
        mQueue=Volley.newRequestQueue(mContext.getApplicationContext());
        StringRequest request=new StringRequest(Flag.HotUniversity, new Response.Listener<String>() {
		@Override
		public void onResponse(String response) {
			String str="";
			try {
				str=new String(response.getBytes("ISO-8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			//异步任务用于将数据存入数据库，因为数据量较大，所以会阻塞主界面，需要异步处理
			new AsyncTask<String, Void, Void>(){
				@Override
				protected Void doInBackground(String... s) {
					try {
						JSONArray array=new JSONArray(s[0]);
						ArrayList<ContentValues> values=new ArrayList<ContentValues>();
						JSONArray a=null;
						for (int i = 0; i < array.length(); i++) {
							a=array.getJSONArray(i);
							ContentValues value=new ContentValues();
							value.put("榜名", a.getString(0));
							value.put("排名", a.getInt(1));
							value.put("院校名称", a.getString(2));
							values.add(value);
						}
						manager.insertHotData(values);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					return null;
				}
				@Override
				protected void onPostExecute(Void result) {
					dialog.dismiss();
					Toast.makeText(mContext, "数据更新成功", 0).show();
				}
			}.execute(str);
		}
		}, new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				dialog.dismiss();
				Toast.makeText(mContext, "数据更新失败", 0).show();
			}
		});
        mQueue.add(request);
		}
		public void disMiss(){
			dialog.dismiss();
		}
		public void show(){
			dialog.show();
		}
}
